﻿using UnityEngine;
using UnityEngine.UI;

public class RenderTool : Singleton<RenderTool>
{
    Camera renderCamera;
    RenderTexture renderTexture;
    GameObject actor;


    /// <summary>
    /// 根据RawImage和一个GO，生成一个渲染相机，输入给RawImage画面
    /// </summary>
    /// <param name="image">raw Image</param>
    /// <param name="go"></param>
    public void AddRenderTex(RawImage image, GameObject go)
    {
        if (renderCamera == null)
        {
            renderCamera = CreateCamera("ModelCamera");
            renderCamera.transform.position = new Vector3(0, 0, 1000);
        }

        renderCamera.gameObject.SetActive(true);
        actor = go;

        go.transform.SetParent(renderCamera.transform, false);
        go.transform.localPosition = new Vector3(0, -1, 2);
        go.transform.localEulerAngles = new Vector3(0, 180, 0);

        // 创建RenderTexture并绑定到摄像机上
        if (renderTexture == null)
        {
            renderTexture = new RenderTexture(1024, 1024, 24);
        }
        renderCamera.targetTexture = renderTexture;
        image.texture = renderTexture;
    }

    public void Close()
    {
        GameObject.Destroy(actor);
        //renderCamera.gameObject.SetActive(false);
    }

    Camera CreateCamera(string name)
    {
        // 创建拍摄用的摄像机
        GameObject go = new GameObject(name);
        Camera _camera = go.AddComponent<Camera>();
        _camera.clearFlags = CameraClearFlags.SolidColor;
        //_camera.cullingMask = LayerMask.GetMask(layerName);
        _camera.backgroundColor = new Color(0, 0, 0, 0);

        return _camera;
    }
}